#define butPin A2

#define butLeft 1
#define butRight 2
#define butSet 3

int const butLeftV = 230;     //Значение кнопки влево
int const butRightV = 500;    //Значение кнопки вправо
int const butSetV = 920;      //Значение кнопки Установка

int const butDiff = 50;       //Отклонение значений

unsigned long butTime = 0;
int butCur = 0;

bool isBut = false;
bool isReady = true;

bool isLeft = false;
bool isRight = false;
bool isSet = false;
bool isLeftLong = false;
bool isRightLong = false;
bool isSetLong = false;

void buttons_init() {
  analogReference(INTERNAL);
}

void buttons_handler() {
  unsigned long ms = millis();
  int button = _curButton();  

  isLeft = false;
  isRight = false;
  isSet = false;
  isLeftLong = false;
  isRightLong = false;
  isSetLong = false;

  
  if(isReady and button > 0) {
    
    if(butTime == 0){
      isBut = true;
      butTime = ms;
      butCur = button;
      isReady = false;
    }   
  }

  if(!isReady and button==0) isReady=true;
  
    unsigned long diff = ms-butTime;
    if((isBut and button == 0) or (isBut and diff > 800)) {
      
      butTime = 0;
      isBut = false;
      
      if( diff < 50 ) {
        butCur = 0;
        return;
      }else if( diff < 500 ) {
        if(butCur == 1) isLeft = true;
        else if(butCur == 2) isRight = true;
        else if(butCur == 3) isSet = true;
        butCur = 0;
        return;
      }else{
        if(butCur == 1) isLeftLong = true;
        else if(butCur == 2) isRightLong = true;
        else if(butCur == 3) isSetLong = true;
        butCur = 0;
        return;
      }
    }
  
  
}

bool button_isLeft(){
  return isLeft;
}

bool button_isRight(){
  return isRight;
}

bool button_isSet(){
  return isSet;
}

bool button_isLeftLong(){
  return isLeftLong;
}

bool button_isRightLong(){
  return isRightLong;
}

bool button_isSetLong(){
  return isSetLong;
}

int _curButton(){
  int v = analogRead(butPin);
  if((butLeftV-butDiff) < v and (butLeftV+butDiff) > v) return butLeft;
  if((butRightV-butDiff) < v and (butRightV+butDiff) > v) return butRight;
  if((butSetV-butDiff) < v and (butSetV+butDiff) > v) return butSet;

  return 0;
}

